package com.ayz.gateway.common.notify;

import cn.hutool.core.lang.Assert;

import java.util.HashSet;
import java.util.concurrent.Executor;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 支持以线程池处理向监听器发布事件
 */
public class SimpleApplicationEventMulticaster extends AbstractApplicationEventMulticaster{
    private Executor executor;
    public SimpleApplicationEventMulticaster() {
    }

    public SimpleApplicationEventMulticaster(Executor executor) {
        this.executor=executor;
    }

    @Override
    public synchronized void multicastEvent(ApplicationEvent event) {
        Assert.notNull(event,"event must not be null!");
        this.multicastEvent(event,event.getClass());
    }
    @Override
    public void multicastEvent(ApplicationEvent event, Class<?> eventType) {
        HashSet<ApplicationListener<?>> applicationListeners = getApplicationListeners(event, eventType);
        if(applicationListeners!=null && !applicationListeners.isEmpty()){
            for (ApplicationListener<?> applicationListener : applicationListeners) {
                if(this.executor!=null){
                    this.executor.execute(()->{invokeListener(applicationListener,event);});
                }else{
                    invokeListener(applicationListener,event);
                }
            }
        }
    }

    private void invokeListener(ApplicationListener applicationListener, ApplicationEvent event) {
        applicationListener.onApplicationEvent(event);
    }

    public void setExecutor(Executor executor) {
        this.executor = executor;
    }

    public Executor getExecutor() {
        return executor;
    }

}
